import * as THREE from 'plug/threejs/three.module';
import {MTLLoader} from "plug/threejs/loaders/MTLLoader";
import {OBJLoader} from "plug/threejs/loaders/OBJLoader";
import {OrbitControls} from "plug/threejs/controls/OrbitControls";
import * as TWEEN from "_@tweenjs_tween.js@18.6.4@@tweenjs/tween.js";

let __this
let container;
let camera, scene, renderer;
let objects = [];
let planeArr = [];
let planenum = 13;
let arr = [[-710, 1390, 0], [-710, 1187, 0], [-710, 969, 0], [-710, 714, 0], [-710, 480, 0], [-357, 973, 0], [0, 973, 0], [382, 959, 0], [845, 1398, 0], [845, 1194, 0], [845, 962, 0], [845, 700, 0], [845, 458, 0]];
let width = (1550 / 1918 * window.innerWidth).toFixed(0);
let height = (850 / 977 * window.innerHeight).toFixed(0);
let mouse = new THREE.Vector2(), selectObject, raycaster = new THREE.Raycaster();
let orbitcontrols;
let flashMaterial = [new THREE.MeshBasicMaterial({
  color: 0xff0000,
  transparent: true,
  opacity: 0.5
}),
  new THREE.MeshBasicMaterial({
    color: 0xffff00,
    transparent: true,
    opacity: 0.5
  }),
  new THREE.MeshBasicMaterial({
    color: 0x0000ff,
    transparent: true,
    opacity: 0.5
  })
];
//0是红色，1是黄色，2是蓝色

let startTime;
let run = false;

export function destroy() {
  run = false;
  TWEEN.removeAll()
}

export function AnimePlay(_this) {
  run = true;
  objects = [];
  planeArr = [];
  planenum = 13;
  mouse = new THREE.Vector2()
  raycaster = new THREE.Raycaster();

  __this = _this
  startTime = new Date().getTime()
  flashMaterial = [new THREE.MeshBasicMaterial({
    color: 0xff0000,
    transparent: true,
    opacity: 0.5
  }),
    new THREE.MeshBasicMaterial({
      color: 0xffff00,
      transparent: true,
      opacity: 0.5
    }),
    new THREE.MeshBasicMaterial({
      color: 0x0000ff,
      transparent: true,
      opacity: 0.5
    })
  ];
  init();
}

function myloadplane(object) {
  let radius = 75, segemnt = 16, rings = 16;

  let sphereMaterial = new THREE.MeshLambertMaterial({
    color: 0xCC0000, transparent: true,
    opacity: 0.1
  });

  let sphere = new THREE.Mesh(
    new THREE.SphereGeometry(radius, segemnt, rings),
    sphereMaterial
  );
  sphere.geometry.verticesNeedUpdate = true;
  sphere.geometry.normalsNeedUpdate = true;

  for (let i = 1; i <= planenum; i++) {
    let ob = object.clone();
    ob.position.x = arr[i - 1][0];
    ob.position.y = arr[i - 1][1] - 800;
    ob.position.z = arr[i - 1][2];
    //ob.castShadow = true;
    //ob.receiveShadow = true;
    scene.add(ob);
    planeArr.push(ob);

    let om = sphere.clone();
    om.position.x = ob.position.x;
    om.position.y = ob.position.y;
    om.position.z = ob.position.z;
    //om.castShadow = true;
    //om.receiveShadow = true;

    om.name = 'pl' + i;
    scene.add(om);
    objects.push(om);
  }
  renderer = new THREE.WebGLRenderer();
  renderer.setSize(width, height);

  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFShadowMap;

  container.appendChild(renderer.domElement);
  initOrbitControl();
  //window.addEventListener( 'resize', onWindowResize, false );

  document.getElementById('anime_ex3').addEventListener('click', onClick, false);
  // falshfun();
  Animate();
}

//轨迹控制器
function initOrbitControl() {
  orbitcontrols = new OrbitControls(camera, renderer.domElement);
  orbitcontrols.enabled = true;
  camera.position.set(0, 200, 2000);
  orbitcontrols.enableDamping = true;
  //是否可以缩放
  orbitcontrols.enableZoom = true;
  //是否自动旋转
  orbitcontrols.autoRotate = false;
  //设置相机距离原点的最远距离
  orbitcontrols.minDistance = 1;
  //设置相机距离原点的最远距离
  orbitcontrols.maxDistance = 3000;

  orbitcontrols.update();
}

function init() {

  container = document.getElementById('anime_ex3');
  // Fov – 相机的视锥体的垂直视野角
  // Aspect – 相机视锥体的长宽比
  // Near – 相机视锥体的近平面
  // Far – 相机视锥体的远平面
  camera = new THREE.PerspectiveCamera(55, width / height, 1, 5000);
  camera.position.z = 2000;
  camera.position.y = 500;

  scene = new THREE.Scene();
  scene.background = new THREE.Color(0x1A2B47);
  scene.fog = new THREE.Fog(0xcce0ff, 500, 10000);
  camera.lookAt(scene.position);


  scene.add(new THREE.AmbientLight(0x666666));

  let light = new THREE.DirectionalLight(0xdfebff, 1);
  light.position.set(50, 200, 100);
  light.position.multiplyScalar(1.3);

  light.castShadow = true;

  light.shadow.mapSize.width = 1024;
  light.shadow.mapSize.height = 1024;

  let d = 300;

  light.shadow.camera.left = -d;
  light.shadow.camera.right = d;
  light.shadow.camera.top = d;
  light.shadow.camera.bottom = -d;

  light.shadow.camera.far = 1000;

  scene.add(light);


  let onProgress = function (xhr) {
    if (xhr.lengthComputable) {
      if (xhr.loaded === xhr.total) {
        __this.loading.close()
      }
    }
  };

  let onError = function () {
  };

  let manager = new THREE.LoadingManager();
  let mtl = new MTLLoader(manager)
    .load('http://cdn.hsueh.club/plane.mtl', function (materials) {
      materials.preload();
      new OBJLoader(manager)
        .setMaterials(materials)
        .load('http://cdn.hsueh.club/plane.obj', function (object) {
          myloadplane(object);
        }, onProgress, onError);
    });
}


//这里变了
function onClick(event) {

  let intersects = getIntersects(event);
  // 获取选中最近的 Mesh 对象
  if (intersects.length !== 0 && intersects[0].object instanceof THREE.Mesh) {
    // 获取 raycaster 和所有模型相交的数组，其中的元素按照距离排序，越近的越靠前

    selectObject = intersects[0].object;
    let name = selectObject.name;
    if ("pl" === name.substring(0, 2)) {
      let num = parseInt(name.substring(2));
      __this.planeNum = "PL" + num + "";
      __this.value = __this.planeArr[num - 1].orderId;
    }
  }
}

//这里变了
function getIntersects(event) {
  event.preventDefault();
  // 通过鼠标点击位置,计算出 raycaster 所需点的位置,以屏幕为中心点,范围 -1 到 1
  let getBoundingClientRect = container.getBoundingClientRect()
  mouse.x = ((event.clientX - getBoundingClientRect.left) / container.offsetWidth) * 2 - 1;
  mouse.y = -((event.clientY - getBoundingClientRect.top) / container.offsetHeight) * 2 + 1;

  //通过鼠标点击的位置(二维坐标)和当前相机的矩阵计算出射线位置
  raycaster.setFromCamera(mouse, camera);

  // 获取与射线相交的对象数组，其中的元素按照距离排序，越近的越靠前
  let intersects = raycaster.intersectObjects(objects);

  //返回选中的对象
  return intersects;
}

function render() {
  let nowTime = new Date().getTime();
  let diff = ((nowTime - startTime) / 100).toFixed(0);

  for (let i = 0; i < planenum; ++i) {
    let key = __this.orderHash[__this.planeArr[i].orderId];
    let roundTime = (diff / (__this.tableData[key].time * 10 / 4)).toFixed(0) % 4;
    objects[i].material = flashMaterial[__this.tableData[key].light[roundTime].id - 1];
  }
  renderer.render(scene, camera);
}

//普通的循环渲染
function Animate() {
  if (run === false) return
  requestAnimationFrame(Animate);
  render();
}
